package logic

import (
	"encoding/json"
	"errors"
	"go.uber.org/zap"
	"io/ioutil"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/wechatpay"
)

type WxCertificates struct {
	Data []struct {
		EffectiveTime      string `json:"effective_time"`
		EncryptCertificate struct {
			Algorithm      string `json:"algorithm"`
			AssociatedData string `json:"associated_data"`
			Ciphertext     string `json:"ciphertext"`
			Nonce          string `json:"nonce"`
		} `json:"encrypt_certificate"`
		ExpireTime string `json:"expire_time"`
		SerialNo   string    `json:"serial_no"`
	} `json:"data"`
}

type CertificateInfo struct {
	SerialNo   string  `json:"serial_no"`
	Publickey  string  `json:"publickey"`
}

type WxCertLogic struct {  }

func NewWxCertLogic() *WxCertLogic {
	return &WxCertLogic{}
}

// 下载微信平台证书 - (定时抓取或判断证书过期时间)
func (logic *WxCertLogic) DownloadCertificate() (*WxCertificates, error) {
	wc := NewSettingLogic().GetPaySetting()
	wxCert := &WxCertificates{}
	respData,err := wechatpay.ApiCertificates(wc)
	if err != nil {
		zap.L().Error("微信平台证书密文下载失败", zap.Error(err))
		return nil, err
	}
	// 密文解析到struct中
	_ = json.Unmarshal([]byte(respData.ToJson()), wxCert)
	// 将获取到的结果写入文件中
	err = ioutil.WriteFile(global.Cfg.Wx.CertPath, []byte(respData.ToJson()),666)
	if err != nil {
		zap.L().Error("微信平台证书密文写入文件失败", zap.Error(err))
		return nil, err
	}
	return wxCert, nil
	// 证书密文 example
	//{
	//	"data":
	//		[{
	//			"effective_time":"2020-06-22T17:56:26+08:00",
	//			"encrypt_certificate":
	//			{
	//				"algorithm":"AEAD_AES_256_GCM",
	//				"associated_data":"certificate",
	//				"ciphertext":"Til01lMgXR09kPJaNxflAuNkOmnolrDUilrfSllUqfWmx53kBPJihClfUNplXEeLV9twABcSWiafyi1VrksL5Q8huDnr0rwgDlPKFiFW7e/JuI/b2smIcJCB4t34QpZFF7x/KlJJuuPqGU+QjTF0H/ZYsAK1scSfWoG4M3DL2u8q/0f1BcWQxlcObnzIg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QxGB2w9wuVJNlFGZOyI7+ZMglgxulZN4cbgf/mDW1zbW2Eg9y5I6AxR9gjEUnOiNG431gCXSWrsE86fM8ynf2rqZ8T2qqsNIB88Z9ztrH3IGMzzSzW1kJTeB5gqkkQzaLzR/5PakD9tV03iZLBAHPiV4UgLqux37uKdVQHf3BRsYkHViyeyGnV47XUUa7L0bfBkEzZn+Rv1w3A+1V986rn66qtBlv5trEfSZnYPf8MH106s+HxOrJnkJPc1wo89n+HBdEA4PVKSItmgTVVYG+2B2V3YoP7pa9ijlPwdE0NsNjXKr1VEaAxYFFqEqqXMjFUcohCZ4tM0O+2PRB2QYA0/Bjid2No7ZI+EBBAls6IKfPoGFJfVmzMJdqGAHeV7dFZcxih3MpyWE3c8mkFYQhQD1KRh+zOEunifVJa0SxrZPgtsta1Gb4JBU8M42d2fnfhHuN2WEdKoR2VBwwqFQT2TsHEhmjKUwkHulOMG0IV8MXK8CpJbPI3MnvshO6ybaH92e5ftRkW3bwiEOpx5HgnM6Eg8rTRaG5Ls+luTCR1GGsnbnGCCLWVu+JRyiVGuycuyW0DUQ65rM9OcUXOud3Z55WatCY6zrSIgRiYNxvptJQ==",
	//				"nonce":"893cb5889f00"
	//			},
	//			"expire_time":"2025-06-21T17:56:26+08:00",
	//			"serial_no":"1BD7AB9E2C24197B7FAD677EE22356B594176D6D"
	//		}]
	//}
}

// 加载微信平台证书
func (logic *WxCertLogic) LoadCertificate() (*WxCertificates, error) {
	wxCert := &WxCertificates{}
	var err error
	var c []byte
	c, err = ioutil.ReadFile(global.Cfg.Wx.CertPath)
	_ = json.Unmarshal(c, wxCert)
	//log.Println("打印测试结果 LoadCertificate", wxCert)
	if len(wxCert.Data) <= 0 { // 证书密文不存在, 下载
		wxCert,err = logic.DownloadCertificate()
		if err != nil {
			return nil, err
		}
	}
	return wxCert, nil
}

// 解密微信平台证书密文
func (logic *WxCertLogic) DecryptCertificate(wxCert *WxCertificates) (*CertificateInfo, error) {

	wc := NewSettingLogic().GetPaySetting()
	if len(wxCert.Data) <= 0 {
		return nil, errors.New("没有找到平台密文证书")
	}

	certsInfo      := wxCert.Data[0]
	cipherText     := certsInfo.EncryptCertificate.Ciphertext
	nonceStr       := certsInfo.EncryptCertificate.Nonce
	associatedData := certsInfo.EncryptCertificate.AssociatedData

	publicKey,err := wechatpay.AesGcmDecrypt(cipherText, nonceStr, associatedData, wc.ApiKeyV3)
	if err != nil {
		return nil, err
	}
	resultData := &CertificateInfo{
		SerialNo:  certsInfo.SerialNo,
		Publickey: publicKey,
	}

	return resultData, nil
}
